package com.jeesite.modules.sd.service;

import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.lang.ObjectUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.modules.sd.common.constants.GlobalEnum;
import com.jeesite.modules.sd.common.constants.MsgTypeEnum;
import com.jeesite.modules.sd.entity.DocDeliverRecord;
import com.jeesite.modules.sd.entity.DocRecv;
import com.jeesite.modules.sd.entity.MsgCodeDTO;
import com.jeesite.modules.sd.entity.MsgManager;
import com.jeesite.modules.sys.entity.EmpUser;
import com.jeesite.modules.sys.entity.Office;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.sys.service.EmpUserService;
import com.jeesite.modules.sys.service.OfficeService;
import com.jeesite.modules.sys.service.UserService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional(readOnly = false)
public class DocRedisService {
    @Autowired
    private UserService userService;
    @Autowired
    private EmpUserService empUserService;
    @Autowired
    private OfficeService officeService;
    @Autowired
    private DocRecvService recvService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private MsgManagerService msgManagerService;
    @Autowired
    private DocDeliverRecordService recordService;

    /**
     * 把要发短信的单位号码存到数据库中
     *
     * @param
     */
    @Transactional(readOnly = false,rollbackFor = Exception.class)
    public void sendInsertRedis(List<DocDeliverRecord> docDeliverRecords) {
        if (CollectionUtils.isEmpty(docDeliverRecords)) {
            throw new RuntimeException("插入失败");
        }
       Date date= new Date();
        List<MsgCodeDTO> msgCodeDTOS = ListUtils.newArrayList();
        DocRecv docRecv = recvService.get(docDeliverRecords.get(0).getDocId());
        Map<String, List<DocDeliverRecord>> recordsMap = docDeliverRecords.stream().collect(Collectors.groupingBy(DocDeliverRecord::getDeliverType));
        boolean send = recordsMap.containsKey(GlobalEnum.RECORD_DELIVER_TYPE_SEND.getKey());
        boolean take = recordsMap.containsKey(GlobalEnum.RECORD_DELIVER_TYPE_DELIVER.getKey());
        StringBuffer stringBuffer = new StringBuffer();
        if (send) {
            List<DocDeliverRecord> sendlist = recordsMap.get(GlobalEnum.RECORD_DELIVER_TYPE_SEND.getKey());
            boolean b = recordService.isExistOffice(GlobalEnum.OFFICE_TYPE_SECRETARIAT.getKey());
            if (!b) {
                throw new RuntimeException("没有保密处");
            }
            User user = recordService.getSecretariatUser();
            if (ObjectUtils.isEmpty(user)) {
                throw new RuntimeException("保密处单位没有人员");
            }
            String deId=sendlist.get(0).getId();
            Office office = new Office();
            sendlist.forEach(sendUnit -> {
                office.setOfficeCode(sendUnit.getRecvUnitCode());
                stringBuffer.append(officeService.get(office).getFullName() + "、");
            });

         //   stringBuffer.append("<<" + docRecv.getDocTitle() + ">>文件已到，请及时送往"+"，于 "+DateUtils.formatDate( sendlist.get(0).getBeforeReturnDate())  +" 2020-08-03 前归还。");
          String context="《" + docRecv.getDocTitle() + "》文件已到，请及时送往"+stringBuffer+"办公室，于 "+DateUtils.formatDate( sendlist.get(0).getBeforeReturnDate())  +"前归还。";
            //村信息到数据库
            MsgManager msgManager = new MsgManager();
            msgManager.setMsgContent(context);
            msgManager.setSendDate(new Date());
            msgManager.setTelphone(user.getMobile());
            msgManager.setMsgType(MsgTypeEnum.MSG_TYPE_SEND.getKey());
            //默认存储失败
            msgManager.setSendStatus(MsgTypeEnum.MSG_TYPE_STATE_FAIL.getKey());
              msgManager.setDocId(deId);
              msgManagerService.save(msgManager);
//            MsgCodeDTO msgCodeDTO1 = new MsgCodeDTO();
//            msgCodeDTO1.setPhone(user.getMobile());
//            msgCodeDTO1.setContent(stringBuffer.toString());
//            msgCodeDTO1.setFlag(deId);
//            msgCodeDTOS.add(msgCodeDTO1);
        }

        if (take) {

            List<DocDeliverRecord> underlist = recordsMap.get(GlobalEnum.RECORD_DELIVER_TYPE_DELIVER.getKey());

            underlist.forEach(docDeliverRecord -> {

                MsgCodeDTO codeDTO = new MsgCodeDTO();
                String unitCode = docDeliverRecord.getRecvUnitCode();
                EmpUser empUser1 = new EmpUser();
                empUser1.setCodes(new String[]{unitCode});
                List<EmpUser> users = empUserService.findUserListByOfficeCodes(empUser1);
                if (CollectionUtils.isEmpty(users)) {
                    Office office2 = officeService.get(unitCode);
                    throw new RuntimeException(office2.getOfficeName() + "单位没有人");
                }
                String userCode = users.get(0).getUserCode();
                User user = userService.get(userCode);


               /* codeDTO.setPhone(user.getMobile());
                codeDTO.setContent(docRecv.getDocTitle() + "文件已到,请" + DateUtils.formatDate(docDeliverRecord.getBeforeTakeDate()) + " 之前领取");
                codeDTO.setFlag(docDeliverRecord.getId());
                msgCodeDTOS.add(codeDTO);*/
                //村信息到数据库
                MsgManager msgManager = new MsgManager();
                msgManager.setMsgContent("《"+docRecv.getDocTitle()+ "》文件已到，请及时领取，于" + DateUtils.formatDate(docDeliverRecord.getBeforeReturnDate()) + "前归还。");
                msgManager.setSendDate(new Date());
                msgManager.setMsgType(MsgTypeEnum.MSG_TYPE_SEND.getKey());
                msgManager.setSendStatus(MsgTypeEnum.MSG_TYPE_STATE_FAIL.getKey());
                msgManager.setTelphone(user.getMobile());
                msgManager.setDocId(docDeliverRecord.getId());
                msgManagerService.save(msgManager);

            });


        }
    }

    /**
     * 查询要发的短信 并删除短信
     *
     * @param
     * @return
     */
    @Transactional(readOnly = false)
    public MsgManager findAndDeleteRedis() {


//        String recordId = redisUtils.list.getFirst("recordId");
//        List<MsgCodeDTO> msgCodeDTO = redisUtils.hash.get("send", "msg_" + recordId);
//
//        redisUtils.hash.delete("send", "msg_" + recordId);
//        redisUtils.list.remove("recordId", 1, recordId);
        //修改数据库中短信发送信息的状态
        MsgManager msgManager=new MsgManager();
        msgManager.setSendStatus(MsgTypeEnum.MSG_TYPE_STATE_FAIL.getKey());
        MsgManager msgOne = msgManagerService.getMsgOne(msgManager);

       //修改文件状态 发送成功
        msgManager.setSendStatus(MsgTypeEnum.MSG_TYPE_STATE_SUCCEED.getKey());
        msgManager.setDocId(msgOne.getDocId());
        msgManagerService.updataMsgStatue(msgManager);


        return msgOne;
    }


}
